package com.atguigu.dga.common.demo;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

public class ThreadDemo {



    public static void main(String[] args) throws InterruptedException {

        // 线程池初始化 看coreSize   如果coreSize不够 进队列 ，队列满了扩容 不能超过maxSize   如果空闲了到达keepalivetime 释放线程 不会低于coreSize
        ThreadPoolExecutor threadPoolExecutor=  new ThreadPoolExecutor(5,20,60, TimeUnit.SECONDS,new LinkedBlockingDeque<>(1000));

        // 1 ，2,3，4,5，6   计算每个数的评分 然后汇总求和
        int[] arr = {1,2,3,4,5,6};
        long l = System.currentTimeMillis();
        List<Integer> resultList=new ArrayList<>();
        List<CompletableFuture<Integer>> futureList=new ArrayList<>();
        for (int n : arr) {
            CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
                //异步逻辑 此处任务会单独开辟线程计算
                int n2 = n * n;
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                return n2;
            },threadPoolExecutor);

            futureList.add(future);
        }
        //把期货兑现货
        resultList = futureList.stream().map(future -> future.join()).collect(Collectors.toList());

        //总耗时
        System.out.println("总耗时 = " + (System.currentTimeMillis() - l));

        Integer sum =0;
        for (Integer i : resultList) {
            sum+=i;
        }
        System.out.println("sum = " + sum);



    }

}
